/**
 * 接收广播.
 *
 * @Creator      : dangqy
 * @Create Date  : 2017-7-12
 * @Since        : 06.00.0000
 * Modifier      :
 * Modified Date :
 * @Dependences  :
 * @Description  :
 */

// ~ Fields
// ====================================================================================================================
var vueObj;
// var BOSH_SERVICE = 'ws://192.168.4.10:7070/ws/';
var BOSH_SERVICE = '';
var connection = null;
var dbHelper = null;

var context = {};
//用户id
var accountName = "";
//用户姓名
var empName = "";
//企业标识
var tenant = "";
//openfire后缀,_企业标识@域名
var STROPHE_SUFFIX = "";
//域名后缀,@域名
var DOMAIN_SUFFIX = "";
//房间后缀,@conference.域名
var ROOM_SUFFIX = "";

// ~ Initialize
// ====================================================================================================================

appcan.ready(function() {

});

// ~ Public Functions
// ====================================================================================================================

//初始化strophe连接
function initChatConn(pwd) {
    context = Supp.MEIP.getContext();
    var account = context.account ? context.account : {};
    //用户信息
    accountName = account.accountName ? account.accountName : "";
    empName = context.employee ? context.employee.empName : "";
    tenant = context.tenant;
    var openfire_config = Supp.LocStorage.getSysVal("openfire_config");
    if (openfire_config) {
        openfire_config = JSON.parse(openfire_config);
        BOSH_SERVICE = "http://" + openfire_config.ip + ":7070/http-bind/";
        STROPHE_SUFFIX = "_" + tenant + "@" + openfire_config.domain;
        ROOM_SUFFIX = "@conference." + openfire_config.domain;
        DOMAIN_SUFFIX = "@" + openfire_config.domain;
    }
    connection = new Strophe.Connection(BOSH_SERVICE);
    connection.connect(accountName + STROPHE_SUFFIX, 'pass', onConnect);
    connection.rawInput = rawInput;
    connection.rawOutput = rawOutput;
}

//连接群聊
function connectChatRoom(roomId) {
    // 发送<presence>元素，加入房间
    connection.send($pres({
        from : accountName + STROPHE_SUFFIX,
        to : roomId + ROOM_SUFFIX + "/" + accountName
    }).c('x', {
        xmlns : 'http://jabber.org/protocol/muc'
    }).tree());

}

/*
 * 发送消息
 * toId:收消息人的账号
 * accountName:收消息人的姓名
 * msg:发送的消息内容
 * chatType:消息类型，包括：chat,voice,img,默认为chat
 */
function sendMsg(toId, accountName, msg, chatType) {
    if (!chatType) {
        chatType = "chat";
    }
    var reply = $msg({
        to : toId + DOMAIN_SUFFIX,
        from : accountName + STROPHE_SUFFIX,
        type : "chat",
        chatType : chatType
    }).cnode(Strophe.xmlElement('body', '', msg));
    connection.send(reply.tree());

}

/*
 * 发送群聊消息
 * toId:群聊id
 * accountName:发消息人的姓名
 * msg:发送的消息内容
 * chatType:消息类型，包括：chat,voice,img,默认为chat
 */
function sendGroupMsg(toId, accountName, msg, chatType) {
    if (!chatType) {
        chatType = "chat";
    }
    var reply = $msg({
        to : toId + ROOM_SUFFIX,
        from : accountName + STROPHE_SUFFIX,
        type : "groupchat",
        chatType : chatType
    }).cnode(Strophe.xmlElement('body', '', msg));
    connection.send(reply.tree());

}

function rawInput(data) {
    // alert('RECV: ' + data);
}

function rawOutput(data) {
    // alert('SENT: ' + data);
}

function xmlInput(data) {
    // alert('RECV: ' + data);
}

function xmlOutput(data) {
    // alert('SENT: ' + data);
}

function onConnect(status) {
    if (status == Strophe.Status.CONNECTING) {
        // log('Strophe is connecting.');
    } else if (status == Strophe.Status.CONNFAIL) {
        // log('Strophe failed to connect.');
        // $('#connect').get(0).value = 'connect';
    } else if (status == Strophe.Status.DISCONNECTING) {
        // log('Strophe is disconnecting.');
    } else if (status == Strophe.Status.DISCONNECTED) {
        // log('Strophe is disconnected.');
        // $('#connect').get(0).value = 'connect';
    } else if (status == Strophe.Status.CONNECTED) {
        // log('Strophe is connected.');
        // log('ECHOBOT: Send a message to ' + connection.jid + ' to talk to me.');
        connection.addHandler(onMessage, null, 'message', null, null, null);
        connection.send($pres().tree());
        //获得该用户可加入的所有群聊
        Supp.ajax({
            url : "/service/mobile/proxy/r/service/eip/integration/supp_message/link/getJoinedRoom",
            success : function(data) {
                if (data.successful) {
                    var list = data.body;
                    var roomIds = [];
                    if (list) {
                        for (var i = 0; i < list.length; i++) {
                            var room = list[i];
                            var roomId = room.deptId;
                            var roomName = room.name;
                            var newRoom = {
                                "roomId" : roomId,
                                "roomName" : roomName
                            };
                            roomIds.push(newRoom);
                        }
                        autoJoinRoom(roomIds);
                    }
                    //得到用户所有的聊天室，存入系统级缓存
                    Supp.LocStorage.setSysVal("MEIP_ROOMIDS", JSON.stringify(roomIds));

                }
            }
        });

    }
}

/*
 * 自动加入房间
 * roomIds 房间ID数组，例如['room1','room2']
 */
function autoJoinRoom(roomIds) {
    if (roomIds) {
        for (var i = 0; i < roomIds.length; i++) {
            var roomId = roomIds[i].roomId;
            // 发送<presence>元素，加入房间
            connection.send($pres({
                from : accountName + STROPHE_SUFFIX,
                to : roomId + ROOM_SUFFIX + "/" + accountName
            }).c('x', {
                xmlns : 'http://jabber.org/protocol/muc'
            }).tree());

        };
    }

}

var notificationId = 1;
function onMessage(msg) {
    var to = msg.getAttribute('to');
    var from = msg.getAttribute('from');
    var chatType = msg.getAttribute('chatType');
    var type = msg.getAttribute('type');
    var elems = msg.getElementsByTagName('body');
    if (elems.length > 0) {
        //如果是群聊，并且发送人是自己，则过滤该条消息

        if (type == "groupchat") {
            var fromJid = from.substring(from.indexOf("/") + 1);
            if (fromJid == accountName || fromJid == accountName + "_" + tenant) {
                return true;
            }
        }

        var body = elems[0];
        var msg = Strophe.getText(body);
        var json = {
            builderId : 0, //long 设置本地通知样式(仅Android有效)
            title : "厚盾移动平台", //本地通知的title
            content : msg, //设置本地通知的content
            extras : {
                key : 1
            }, //额外的数据信息extras为json字符串
            notificationId : notificationId, //int 设置本地通知的ID
            broadCastTime : 1000//long 设置本地通知延迟触发时间，毫秒为单位，如设置10000为延迟10秒添加通知
        };
        notificationId++;
        // uexJPush.addLocalNotification(JSON.stringify(json));
        //收到消息就写入数据库
        var chat_save = {};
        chat_save.chatId = Supp.MEIP.getUUID();
        //发送人empid
        var fromEmpId = "";
        //群聊-发送人id
        var roomFromId = "";
        //群聊id
        var roomId = "";
        //发送人id，带企业标识
        var fromId = "";
        if (from) {
            if (from.indexOf("@") > 0) {
                fromId = from.substring(0, from.indexOf("@"));
            }
        }
        if (to) {
            if (to.indexOf("@") > 0) {
                to = to.substring(0, to.indexOf("@"));
            }
        }
        var jidType = 1;
        chat_save.fromId = fromId;
        chat_save.toId = to;
        chat_save.toName = empName;
        if (!chatType) {
            chatType = "chat";
        }
        if (chatType == "voice") {
            chat_save.isRead = 'F';
        } else {
            chat_save.isRead = 'T';
        }
        if (type == "groupchat") {
            chat_save.isMUC = "T";
            if (from) {
                roomId = fromId;
                if (from.indexOf("/") > 0) {
                    roomFromId = from.substring(from.indexOf("/") + 1);
                }
                if (roomFromId.indexOf("_" + tenant) < 0) {
                    roomFromId = roomFromId + "_" + tenant;
                }
            }
            chat_save.roomId = roomId;
            chat_save.fromId = roomFromId;
        } else {
            chat_save.isMUC = "F";
        }

        if (chat_save.fromId.indexOf("_" + tenant) > 0) {
            fromEmpId = chat_save.fromId.substring(0, chat_save.fromId.indexOf("_" + tenant));
        }

        chat_save.chatType = chatType;
        chat_save.msg = msg;
        //判断是否是图片或语音，如果是，则下载到本地
        if (chatType == "voice" || chatType == "img") {
            var fileId = msg;
            var fileName = "";
            if (chatType == "voice") {
                fileId = fileId.substring(0, fileId.indexOf("|"));
                fileName = fileId + ".amr";
            } else {
                fileName = fileId + ".jpg";
            }
            var savePath = 'wgt://files/download/' + fileName;
            uexFileMgr.cbIsFileExistByPath = function(opId, dataType, data) {
                if (data == "0") {
                    Supp.System.download(fileId, savePath, "F");
                }
            }
            uexFileMgr.isFileExistByPath(savePath);
        }

        chat_save.inTime = Supp.Text.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
        //查询fromname
        var fromName = Supp.LocStorage.getVal("chat_" + fromEmpId);
        if (!fromName) {
            Supp.ajax({
                url : "/service/mobile/proxy/r/service/eip/integration/supp_message/link/getNameOfJid",
                data : {
                    jid : fromEmpId,
                    type : jidType
                },
                chat : chat_save,
                fromEmpId : fromEmpId,
                success : function(data) {
                    if (data.successful) {
                        var _chat = this.chat;
                        var _fromName = data.body;
                        _chat.fromName = _fromName;
                        Supp.LocStorage.setVal("chat_" + this.fromEmpId, _fromName);
                        getDbHelper().saveOrUpdate({
                            "table" : "meip_chat",
                            "data" : _chat,
                            "callback" : function(err, data, dataType, optId) {
                                appcan.window.evaluatePopoverScript("contact", "content", "initChatWidget()");
                            }
                        });
                        appcan.window.evaluateScript("chatting", "receiveMsg(" + JSON.stringify(_chat) + ")");
                        appcan.window.evaluateScript("chatting_room", "receiveMsg(" + JSON.stringify(_chat) + ")");
                    }
                }
            });
        } else {
            chat_save.fromName = fromName;
            getDbHelper().saveOrUpdate({
                "table" : "meip_chat",
                "data" : chat_save,
                "callback" : function(err, data, dataType, optId) {
                    appcan.window.evaluatePopoverScript("contact", "content", "initChatWidget()");
                }
            });
            appcan.window.evaluateScript("chatting", "receiveMsg(" + JSON.stringify(chat_save) + ")");
            appcan.window.evaluateScript("chatting_room", "receiveMsg(" + JSON.stringify(chat_save) + ")");
        }

        //发送通知
        // appcan.window.publish("MEIP_ReceiveMsg");

    }

    // we must return TRUE to keep the handler alive.
    // returning false would remove it after it finishes.
    return true;
}

//获取数据操作助手
function getDbHelper() {
    if (dbHelper == null) {
        dbHelper = Supp.MDB.create();
    }

    return dbHelper;
}